import {SeniorFileContent, SeniorFileItem} from "@/entity/SeniorFileItem";
import {defineStore} from "pinia";
import {group, map} from "@/utils/ArrayUtil";
import {listByAsync, removeOneByAsync, saveListByAsync, saveOneByAsync} from "@/utils/utools/DbStorageUtil";
import LocalNameEnum from "@/enumeration/LocalNameEnum";
import MessageBoxUtil from "@/utils/model/MessageBoxUtil";
import {useSnowflake} from "$/util";
import {useSeniorSearchStore} from "@/store/components/SeniorSearchStore";


export const useSeniorFileItemStore = defineStore("SeniorFileItem", () => {
  const items = ref(new Array<SeniorFileItem>());
  const rev = ref();

  const itemMap = computed(() => {
    const r = map(items.value, 'id');
    r.set('0', {
      id: '0',
      name: '根目录',
      folder: true,
      parentId: '',
      order: 0,
      createdAt: 0
    });
    return r;
  });
  const itemGroupMap = computed(() => group(items.value, 'parentId'));

  const init = async () => {
    const res = await listByAsync<SeniorFileItem>(LocalNameEnum.LIST_SENIOR_FILE_ITEM);
    items.value = res.list;
    rev.value = res.rev;
  }
  init().then(() => console.log("SeniorFileItemStore initialized."));

  const save = async () => {
    rev.value = saveListByAsync(LocalNameEnum.LIST_SENIOR_FILE_ITEM, items.value, rev.value);
  }

  const create = async (parentId: string, folder: boolean) => {
    const name = await MessageBoxUtil.prompt("请输入文件" + (folder ? "夹" : "") + "名", "创建文件" + (folder ? "夹" : ""));
    const id = useSnowflake().nextId();
    items.value.push({
      id,
      folder,
      parentId,
      name,
      createdAt: Date.now(),
      order: (itemGroupMap.value.get(parentId)?.length || 0) + 1
    });
    await save();
    // 如果是文件
    if (!folder) {
      // 创建文件内容
      await saveOneByAsync<SeniorFileContent>(LocalNameEnum.ITEM_SENIOR_FILE_ITEM_ + id, {
        content: '',
        size: 30
      });
    }
  }

  const rename = async (item: SeniorFileItem) => {
    const suffix = item.folder ? "夹" : "";
    const newName = await MessageBoxUtil.prompt("请输入新的" + suffix + "文件名", "重命名", {
      inputValue: item.name
    });
    const index = items.value.findIndex(i => i.id === item.id);
    if (index === -1) return Promise.reject(new Error("文件" + suffix + "未找到"));
    items.value[index].name = newName;
    await save();
  }

  const remove = async (item: SeniorFileItem) => {
    const suffix = item.folder ? "夹" : "";
    await MessageBoxUtil.confirm(`确定要删除此文件${suffix}吗？`, "删除文件" + suffix);
    const index = items.value.findIndex(i => i.id === item.id);
    if (index === -1) return Promise.reject(new Error("文件" + suffix + "未找到"));
    items.value.splice(index, 1);
    await save();
    if (!item.folder) {
      await removeOneByAsync(LocalNameEnum.ITEM_SENIOR_FILE_ITEM_ + item.id);
    }
    // 关闭打开的文件
    useSeniorSearchStore().onFileItemClose(item.id);
  }


  return {
    items, itemMap, itemGroupMap,
    create, rename, remove
  }

})
